﻿using Framework.Components;
using Framework.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ServiceHelper
{
    public partial class MainForm : Form
    {
        protected WriteFileConfig config;

        public MainForm()
        {
            // 初始化窗口
            InitializeComponent();

            // 初始化参数
            var curPath = AppDomain.CurrentDomain.BaseDirectory; //启动程序路径
            string logPath = curPath + "/logs/";
            Log.Instance.Handler = new Log.FileLogHandler(logPath, "hlog");
            Log.Info("程序路径: " + Path.GetFullPath("."));
            Log.Info("日志路径: " + Path.GetFullPath(logPath));
            Log.Info("是否是管理员运行: " + CmdUtils.IsAdministrator());

            // 获取临时目录路径  
            string tempFile = WriteFileConfig.GetAppTempFile();
            config = new WriteFileConfig(tempFile);
            Log.Info("配置路径: " + tempFile);

            // 记录时间
            config.Set("PrevTime", DateTime.Now.ToLocalTime().ToString("yyyy/MM/dd HH:mm:ss"));
            
            // 记录值
            EditSeviceName.Text = config.Get("SeviceName", "CmdSevice");
            EditExePath.Text = config.Get("ExePath", "CmdSevice.exe");
            EditArgs.Text = config.Get("Args", "-r start.bat -s stop.bat");
        }


        /// <summary>
        /// 获取服务字段
        /// </summary>
        private string GetExeString()
        {
            var exePath = EditExePath.Text;
            if (string.IsNullOrEmpty(exePath))
            {
                exePath = "unknown";
            }
            // 参数
            var args = EditArgs.Text;
            args = (!string.IsNullOrEmpty(args)) ? args : "";
            args = args.Replace("\r\n", " ");
            args = args.Replace("\r", " ");
            args = args.Replace("\n", " ");

            return exePath + " " + args; 
        }

        /// <summary>
        /// 注册服务
        /// </summary>
        private void BtnReg_Click(object sender, EventArgs e)
        {
            // 服务名称
            var serviceName = EditSeviceName.Text;
            if (string.IsNullOrEmpty(serviceName))
            {
                MessageBox.Show(this, "服务名为空!", "错误");
                return;
            }
            // 程序路径
            var exePath = EditExePath.Text;
            if (string.IsNullOrEmpty(exePath))
            {
                MessageBox.Show(this, "程序路径为空!", "错误");
                return;
            }
            // 参数
            var exeStr = GetExeString();

            // 注册服务
            var curPath = AppDomain.CurrentDomain.BaseDirectory; //启动程序路径
            var cmdStr = string.Format("sc create {0} binPath= \"{1}\" start= auto", serviceName, exeStr);
            // MessageBox.Show(this, cmdStr, "提示");

            try
            {
                string retStr = CmdUtils.Execute("cmd.exe", "", new string[] { cmdStr, }, curPath);
                Log.Info("注册结果: \r\n" + retStr);
            }
            catch (Exception ex)
            {
                Log.Error("注册服务错误! " + cmdStr, ex);
                MessageBox.Show(this, "执行操作错误: " + ex.ToString(), "错误");
            }
        }

        private void BtnUnReg_Click(object sender, EventArgs e)
        {
            // 服务名称
            var serviceName = EditSeviceName.Text;
            if (string.IsNullOrEmpty(serviceName))
            {
                MessageBox.Show(this, "服务名为空!", "错误");
                return;
            }

            // 注销服务
            var curPath = AppDomain.CurrentDomain.BaseDirectory; //启动程序路径
            var cmdStr = string.Format("sc delete {0}", serviceName);
            // MessageBox.Show(this, cmdStr, "提示");

            try
            {
                string retStr = CmdUtils.Execute("cmd.exe", "", new string[] { cmdStr, }, curPath);
                Log.Info("注销结果: \r\n" + retStr);
            }
            catch (Exception ex)
            {
                Log.Error("注销服务错误! " + cmdStr, ex);
                MessageBox.Show(this, "执行操作错误: " + ex.ToString(), "错误");
            }
        }

        /// <summary>
        /// 选择程序文件
        /// </summary>
        private void BtnExePath_Click(object sender, EventArgs e)
        {
            // 打开文件选择窗口
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "所有文件|*.*";
            ofd.ValidateNames = true;
            ofd.CheckPathExists = true;
            ofd.CheckFileExists = true;
            if (ofd.ShowDialog() == DialogResult.Cancel)
            {
                return; //取消
            }
            // 执行处理
            string strFileName = ofd.FileName;
            //其他代码
            EditExePath.Text = strFileName;

        }

        /// <summary>
        /// 添加参数路径
        /// </summary>
        private void BtnArgs_Click(object sender, EventArgs e)
        {
            // 打开文件选择窗口
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "所有文件|*.*";
            ofd.ValidateNames = true;
            ofd.CheckPathExists = true;
            ofd.CheckFileExists = true;
            if (ofd.ShowDialog() == DialogResult.Cancel)
            {
                return; //取消
            }
            // 执行处理
            string strFileName = ofd.FileName;
            //其他代码
            var nowArgs = EditArgs.Text;
            if (string.IsNullOrEmpty(nowArgs))
            {
                EditArgs.Text = strFileName;
                return;
            }
            // 添加参数
            EditArgs.Text = nowArgs + " " + strFileName;
        }

        private void TipCmdStr_Popup(object sender, PopupEventArgs e)
        {
            // 组件更新
            // UpdateTip();
        }

        /// <summary>
        /// 窗口定时器
        /// </summary>
        private void TimeUpdate_Tick(object sender, EventArgs e)
        {
            UpdateTip();
            SaveConfig();
        }

        /// <summary>
        /// 保存参数
        /// </summary>
        private void SaveConfig()
        {
            config.Set("SeviceName", EditSeviceName.Text);
            config.Set("ExePath", EditExePath.Text);
            config.Set("Args", EditArgs.Text);
        }

        /// <summary>
        /// 更新提示
        /// </summary>
        private void UpdateTip()
        {
            // 悬浮提示
            var tipStr = "当前运行参数: " + GetExeString();
            TipCmdStr.SetToolTip(this, tipStr);
            TipCmdStr.SetToolTip(BtnReg, tipStr);
            TipCmdStr.SetToolTip(EditExePath, tipStr);
            TipCmdStr.SetToolTip(EditArgs, tipStr);
        }
    }
}
